//
//  MyRefreshControl.swift
//  自定义下拉控件
//
//  Created by 王炯 on 16/7/26.
//  Copyright © 2016年 王炯. All rights reserved.
//

import UIKit

// 代表当前控件的状态
enum SHRefreshControlState: Int
{
    // 正常
    case Normal = 0
    // 下拉中
    case Pulling = 1
    // 刷新中
    case Refreshing = 2
}


//自定义的下拉刷新控件继承自UIControl类
class MyRefreshControl: UIControl
{
    
    //定义属性，记录父类scrollView
    var scrollView: UIScrollView?
    
    /*
    var superViewOffset:CGFloat?{
        
        didSet
        {
            guard let offsetY = superViewOffset else
            {
               return
            }
            
            getRefreshControlState(offsetY)
            
        }
        
    }
    */
    
    // 记录当前状态
    var shState:SHRefreshControlState = .Normal
    {
        didSet{
            
            switch shState
            {
            case .Normal:
                messageLabel.text = "正常"
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    self.pullImageView.transform = CGAffineTransformIdentity
                })
                
                // 判断上一个状态为刷新中
                //利用didSet中特有的oldValue记录当前值改变之前时的旧值
                if oldValue == .Refreshing
                {
                    UIView.animateWithDuration(0.25, animations: { () -> Void in
                        self.scrollView?.contentInset.top -= 50
                        }, completion: { (_) -> Void in
                            // 显示箭头
                            self.pullImageView.hidden = false
                            // 停止动画
                            self.indicatorView.stopAnimating()
                    })
                }
                
            case .Pulling:
                //print("下拉中")
                messageLabel.text = "下拉中"
                
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    self.pullImageView.transform = CGAffineTransformMakeRotation(CGFloat(-3*M_PI))
                    
                })
                
            case .Refreshing:
                messageLabel.text = "刷新中"
                // 设置动画 增加scrollView 滑动距离
                // 隐藏箭头
                pullImageView.hidden = true
                // 菊花开始动画
                indicatorView.startAnimating()
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    self.scrollView?.contentInset.top += 50
                    
                    }, completion: { (_) -> Void in
                        
                        
                        // 告知外界可以刷新了
                        //UIControl自带的方法sendActionsForControlEvents,告知外界valueChanged，与 self.refreshControl.addTarget(self, action: #selector(HomeController.refreshAction), forControlEvents: UIControlEvents.ValueChanged)相对应
                        self.sendActionsForControlEvents(UIControlEvents.ValueChanged)
                        
                        
                        
                })
            }
        }
    }
    
    // MARK: - 供外界调用的方法
    func endRefreshing()
    {
        // 01 当前的状态改成正常
        // 02 减去50
        shState = .Normal
    }
    
    
    // MARK: - 懒加载控件
    private lazy var messageLabel: UILabel = {
        let lab = UILabel()
        lab.text = "正常"
        lab.textColor = UIColor.whiteColor()
        lab.font = UIFont.systemFontOfSize(14)
        return lab
    }()
    // 箭头
    private lazy var pullImageView: UIImageView = UIImageView(image: UIImage(named: "tableview_pull_refresh"))
    // 菊花
    private lazy var indicatorView: UIActivityIndicatorView = {
        let view = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.White)
        return view
    }()
    

    //自定义大小
    override init(frame: CGRect)
    {
        super.init(frame: CGRect(x: 0, y: -50, width: UIScreen.mainScreen().bounds.width, height: 50))
        
        //重新设置UI界面
        self.setUpUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func setUpUI()
    {
        self.backgroundColor = UIColor.orangeColor()
        
        // 添加控件
        addSubview(messageLabel)
        addSubview(pullImageView)
        addSubview(indicatorView)
        
        messageLabel.translatesAutoresizingMaskIntoConstraints = false
        
        addConstraint(NSLayoutConstraint(item: messageLabel, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.CenterX, multiplier: 1, constant: 0))
        addConstraint(NSLayoutConstraint(item: messageLabel, attribute: NSLayoutAttribute.CenterY, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.CenterY, multiplier: 1, constant: 0))
        
        pullImageView.translatesAutoresizingMaskIntoConstraints = false
        
        addConstraint(NSLayoutConstraint(item: pullImageView, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.CenterX, multiplier: 1, constant: -35))
        addConstraint(NSLayoutConstraint(item: pullImageView, attribute: NSLayoutAttribute.CenterY, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.CenterY, multiplier: 1, constant: 0))
        
        indicatorView.translatesAutoresizingMaskIntoConstraints = false
        
        addConstraint(NSLayoutConstraint(item: indicatorView, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.CenterX, multiplier: 1, constant: -35))
        addConstraint(NSLayoutConstraint(item: indicatorView, attribute: NSLayoutAttribute.CenterY, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.CenterY, multiplier: 1, constant: 0))
    }
    

    //1-方法1:监控当前的控件要加载到哪一个父控件上
    override func willMoveToSuperview(newSuperview: UIView?)
    {
        //判断父View是否是可以滚动的scrollView
        guard let scrollView = newSuperview as? UIScrollView else
        {
            return
        }
        
        //2-思想1:利用KVO的思想来监控父view的刷新状况
        //此时获取到的self.scrollView为父View
        self.scrollView = scrollView
        
        //定义方法来监控父类view的contentOffsize
        self.scrollView?.addObserver(self, forKeyPath: "contentOffset", options: NSKeyValueObservingOptions.New, context: nil)
        
    }
    
    
    //KVO监听事件的方法
    //获取scrollView 的变化状态
    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>)
    {
        
        getRefreshControlState(self.scrollView!.contentOffset.y)
    }
    
    /*
     
     - 当用户拖动tableView 而且没有松手
     - 当contentOffset.y > -114 显示正常 且当前状态为下拉中
     - 当contentOffset.y <= -114 下拉中 且当前的状态为正常
     - 当用户拖动tableView 而且松手了
     -  如果当前的状态为 下拉中   ---》刷新中
     - 如果用户松手了 而且当前的状态为下拉中 才能进入刷新中
     */
    func getRefreshControlState(contentOffsetY: CGFloat)
    {
        //监控到父类scrollView在y轴方向上的偏移量
        //print(contentOffsetY)
        
        
        // -64
        let contentInsetTop = self.scrollView?.contentInset.top ?? 0
        
        
        //当用户正在拖动父类控件时
        if self.scrollView!.dragging
        {
            //上
            if contentOffsetY > -contentInsetTop - 50 && shState == .Pulling
            {
                shState = .Normal
            }
            //下
            else if contentOffsetY <= -contentInsetTop - 50 && shState == .Normal
            {
                shState = .Pulling
            }
            
        }
        else
        {
            // 代表用户松手了
            if shState == .Pulling
            {
                shState = .Refreshing
            }
            
        }
    }

}
